<template>
  <div class="diff-container">
    <!-- 新增导航按钮区域 -->
    <div class="diff-navigation">
      <button @click="prevDiff" :disabled="!hasDiff">上一个差异</button>
      <button @click="nextDiff" :disabled="!hasDiff">下一个差异</button>
      <span v-if="hasDiff">({{ currentDiffIndex + 1 }}/{{ diffCount }})</span>
    </div>
    <!-- 原有差异显示区域 -->
    <div id="myDiffElement"></div>
  </div>
</template>

<script setup>
import { createPatch } from 'diff'
import  { Diff2HtmlUI } from 'diff2html/lib/ui/js/diff2html-ui'
import "diff2html/bundles/css/diff2html.min.css";
import { ref, onMounted, nextTick, computed } from 'vue'

// 定义组件属性
defineProps({
    msg: String,
})
const currentDiffIndex = ref(-1)  // 当前差异索引
const diffElements = ref([])      // 存储所有差异元素
let diff2Elements = ref([])
const diffCount = ref(0)          // 差异总数
const hasDiff = computed(() => diffCount.value > 0)
// 上一个差异
typeof prevDiff !== 'undefined' && prevDiff
function prevDiff() {
  if (diffElements.value.length === 0) return

  // 移除当前差异高亮
  removeHighlight()

  // 计算上一个差异索引（循环）
  currentDiffIndex.value = 
    currentDiffIndex.value === 0 
      ? diffElements.value.length - 1 
      : currentDiffIndex.value - 1

  // 高亮并滚动到差异位置
  highlightCurrentDiff()
}

// 下一个差异
typeof nextDiff !== 'undefined' && nextDiff
function nextDiff() {
  if (diffElements.value.length === 0) return

  // 移除当前差异高亮
  removeHighlight()

  // 计算下一个差异索引（循环）
  currentDiffIndex.value = 
    currentDiffIndex.value === diffElements.value.length - 1 
      ? 0 
      : currentDiffIndex.value + 1

  // 高亮并滚动到差异位置
  highlightCurrentDiff()
}

// 移除所有差异高亮
function removeHighlight() {
  diffElements.value.forEach(el => {
    el.classList.remove('current-diff')
  })
  diff2Elements.value.forEach(el => {
    el.classList.remove('current-diff')
  })
}

// 高亮当前差异并滚动到视图
function highlightCurrentDiff() {
  const currentEl = diffElements.value[currentDiffIndex.value]
  const currentEl2 = diff2Elements.value[currentDiffIndex.value]
  if (currentEl) {
    currentEl.classList.add('current-diff')
    currentEl2.classList.add('current-diff')
    currentEl.scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    })
  }
}

// 获取所有差异元素

function getDiffElements() {
  // 使用diff2html的CSS类选择器定位所有变更行
  diffElements.value = Array.from(document.querySelectorAll('.d2h-del.d2h-change .d2h-code-side-line'))//,.d2h-code-side-line.d2h-code-side-emptyplaceholder
  diff2Elements.value = Array.from(document.querySelectorAll('.d2h-ins.d2h-change .d2h-code-side-line'))
}

onMounted(async () => {
    // 示例JSON对象1 - 用于比对的原始数据
    const obj1 = {
        "responseId": "1737028341676815839",
        "sessionId": "",
        "phone": "13552569078",
        "userName": "",
        "responseContent": "您请注意，以上资料来源于公开数据，由AI生成内容供参考。",
        "recommend": "",
        "requestContent": "结婚登记",
        "historyContent": "历史记录",
        "responseTime": "2024-09-18 19:22:07",
        "conversationId": "00a38ef2dfc6480c8d802b3e73fe4eff",
        "isComment": 0,
        "nextOptions": [
            {
                "id": "北京市朝阳区民政局-3",
                "value": "北京市朝阳区民政局",
                "level": 3
            }
        ],
        "postFix": "",
        "nodeType": "2"
    };

    // 示例JSON对象2 - 用于比对的修改后数据
    const obj2 = {
        "responseId": "1737028341676815840",
        "sessionId": "",
        "phone": "13552569078",
        "userName": "",
        "responseContent": "您想了解“结婚登记”哪方面的办理内容：",
        "recommend": "",
        // "requestContent": "北京市朝阳区民政局",
        "historyContent": "历史记录",
        "responseTime": "2024-09-18 19:22:08",
        "conversationId": "00a38ef2dfc6480c8d802b3e73fe4eff",
        "isComment": 0,
        "nextOptions": [
            {
                "id": "申请条件-4",
                "value": "申请条件",
                "level": 4
            },
            {"id": "申请材料-4","value": "申请材料","level": 4},
            {"id": "办理地点，时间及联系方式-4","value": "办理地点，时间及联系方式","level": 4},
            {"id": "办理流程-4","value": "办理流程","level": 4}
        ],
        "postFix": "\n请注意，此信息仅作参考，详细办理流程请向相关部门咨询。",
        "nodeType": "2"
    };

    // 将JSON对象转换为格式化字符串进行比较（缩进2个空格，便于阅读差异）


  const text1 = JSON.stringify(obj1, null, 2);
  const text2 = JSON.stringify(obj2, null, 2);
  const diffString = createPatch('test2', text2,text1,  '原始数据', '修改后数据');
  const targetElement = document.getElementById('myDiffElement');

  // ... 原有configuration配置保持不变 ...
  const configuration = {
        // 是否显示文件列表（当比较单个文件时建议设为false）
        drawFileList: false,
        // 是否允许切换文件列表的显示/隐藏状态
        fileListToggle: false,
        // 文件列表初始是否可见
        fileListStartVisible: false,
        // 是否允许切换文件内容的显示/隐藏状态
        fileContentToggle: false,
        // 差异匹配模式：'lines'（行级匹配）| 'words'（单词级匹配）| 'none'（无匹配）
        matching: 'lines',
        // 输出格式：'side-by-side'（并排显示）| 'line-by-line'（行内对比显示）
        outputFormat: 'side-by-side',
        // 是否启用左右面板同步滚动
        synchronisedScroll: true,
        // 是否高亮显示差异部分
        highlight: true,
        // 当没有差异时是否渲染空内容
        renderNothingWhenEmpty: false,
    };

  const diff2htmlUi = new Diff2HtmlUI(targetElement, diffString, configuration);
  diff2htmlUi.draw();
  diff2htmlUi.highlightCode();

  // 新增：等待DOM更新后获取差异元素
  await nextTick()
 getDiffElements()
  diffCount.value = diffElements.value.length
  // 默认选中第一个差异
  if (diffCount.value > 0) {
    currentDiffIndex.value = 0
    highlightCurrentDiff()
  }
})
</script>

<style scoped>
diff-navigation {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.diff-navigation button {
  padding: 6px 12px;
  cursor: pointer;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
}

.diff-navigation button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 新增差异高亮样式 */
:deep(.current-diff) {
  border: 2px solid #ff4400 !important;

}


/* 原有样式保持不变 */
.d2h-code-side-line {
    display: none;
}
</style>